package com.divine.wn.pt.action;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.divine.wn.pt.form.LoginForm;
import com.divine.wn.pt.vo.BackUserVO;

public class LoginAction extends BaseAction {
	
	//用户注销
	public ActionForward forwardLogin(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		request.getSession().invalidate();
		return mapping.findForward("fail");
	}
	
	//转向用户修改密码
	public ActionForward toEditPassword(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		LoginForm loginForm = (LoginForm) form;

		if (backUser == null) {
			response.sendRedirect("login.do?callMethod=forwardLogin");
			return null;
		}
		
		loginForm.setBackUser(backUser);
		return mapping.findForward("password");
	}
	
	//用户修改密码
	public ActionForward updatePassword(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {

		LoginForm loginForm = (LoginForm) form;
		backUserService.updatePassword(loginForm.getBackUser());
		
		request.setAttribute("passwordSuccess", "true");
		
		return mapping.findForward("password");
	}
	
	
	
	
	//用户登录，如果是业务员则跳转到填单页面，其余转到待处理数据页面
	public ActionForward login(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		
		LoginForm loginForm = (LoginForm) form;
		BackUserVO cbackUser = loginForm.getBackUser();
		
		BackUserVO backUserVO=backUserService.getBackUser(cbackUser);
		// 如果用户不存在
		if (backUserVO ==null) {
			if("firstLogin".equals(request.getParameter("firstLogin"))){
				request.setAttribute("userError", "用户名或者密码错误，请不要非法登录系统！");
			}
			return mapping.findForward("fail");
		}else{
			session.setAttribute("buser", backUserVO);
			response.sendRedirect("writeReceipt.do?callMethod=toUserPage");
			return null;
			
		}

		
	}

}
